package com.wolfman.wolfchat.interceptor;

import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSON;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.wolfman.wolfchat.po.User;
import com.wolfman.wolfchat.utils.ErrorResponseUtil;
import com.wolfman.wolfchat.utils.JwtUtil;
import com.wolfman.wolfchat.utils.ThreadLocalUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Title
 * @Description
 * @Author WolfMan
 * @Date 2022/1/15 0:41
 * @Email 2370032534@qq.com
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        String token = request.getHeader("token");
        if (token == null) {
            return true;
        }
        //token不存在
        if ("".equals(token)) {
            ErrorResponseUtil.setResponse(response, "没有token", HttpStatus.HTTP_FORBIDDEN);
            return false;
        }
        DecodedJWT decodedJwt = JwtUtil.verifyJwt(token);
        //token无效
        if (decodedJwt == null) {
            ErrorResponseUtil.setResponse(response, "token无效", HttpStatus.HTTP_FORBIDDEN);
            return false;
        }
        //token过期
        if (JwtUtil.isExpired(decodedJwt)) {
            ErrorResponseUtil.setResponse(response, "token过期", HttpStatus.HTTP_FORBIDDEN);
            return false;
        }
        //保存到线程上下文中
        ThreadLocalUtil.setUser(JSON.parseObject(decodedJwt.getSubject(), User.class));
        return true;
    }


}